// var User = require('../models/user');
// exports.getUser = function(req, res) {
//     var userid = req.params.userid;
//     var user = new User();
//     user.find(userid,function(err,result){
//         if(err){
//             res.send('没有找到userid为'+userid+'的任务');
//         }
//         else if(undefined!=result){ // 增加这个判断，否则在没有查询到的情况下，Node.js会挂掉
//             res.send(result.length === 1 ? result[0]:result);
//         }
//         else{
//             res.end("Error");
//         }
//     });
// };
var db = require('../config/basicConnection');
var $sqlCommands = require('../config/sqlCommand');
var dir  = require("../config/dir");
var formidable = require('formidable'),
    fs = require('fs');


/**
 * 增加用户Action
 */
function addUserAction(req, res, next) {
    db.query($sqlCommands.user_status.findMaxOne,
        function (err, result) {
            if (err) {
                result = {
                    err: err
                }
            }
            req.body['id'] = result[0].maxid + 1;
            var param = req.body || req.query || req.params;
            db.queryArgs($sqlCommands.user_status.insertOne,
                [param.id, param.name, param.address, param.age, param.icon, param.discount, param.creationTime, param.sex, param.status,param.password],
                function (err, result) {
                    if (err) {
                        console.log(err)
                    }
                    // else{
                    //     res.json({
                    //         msg:"插入成功"
                    //     })
                    // }
                    db.doReturn(res, result);
                }
            );
        }
    );
}

/**查找所有用户
 *
 */
function findAllAction(req, res, next) {
    db.query($sqlCommands.user_status.findAll,
        function (err, result) {
            if (err) {
                result = {
                    msg: 'failed'
                };
            }
            // 以json形式，把操作结果返回给前台页面
            // console.log(result)
            db.doReturn(res, result)
        }
    );
}

/**删除用户by身份证id
 *
 */
function deleteUserById(req, res, next) {
    var param = req.body || req.query || req.params;
    db.queryArgs($sqlCommands.user_status.deleteUserById,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            else {
                result = {
                    msg: '删除成功'
                }
            }
            db.doReturn(res, result);
        }
    );
}

/**
 * 查找某用户
 *
 */
function findOneAction(req, res, next) {
    // 获取前台页面传过来的参数
    var param = req.body || req.params || req.query;
    // 执行Query
    // console.log(param)
    db.queryArgs($sqlCommands.user_status.findOne,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            console.log(result)
            db.doReturn(res, result);
        }
    );
}

function findOneByInvi(req, res, next) {
    // 获取前台页面传过来的参数
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.findOneByInvi,
        [param.inviCode],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

// 改动某用户信息
function updateOneInfoAction(req, res, next) {
    var param = req.body || req.params || req.query;
    // console.log(param.id)
    // 执行Query
    db.queryArgs($sqlCommands.user_status.updateOneInfoAction,
        [param.name, param.address, param.age, param.icon, param.grade, param.creationTime, param.sex, param.id],
        function (err, result) {
            // console.log(param)
            if (err) {
                console.log(err)
            }
            else {
                result = {
                    msg: '修改成功'
                }
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

// 显示所有1.2级的用户
function lessThan3G(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.findOne,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

function uploader(req, res, next) {
    var id;
    var form = formidable.IncomingForm({
        encoding: 'utf-8',//上传编码
        uploadDir: "public/files",//上传目录，指的是服务器的路径，如果不存在将会报错。
        keepExtensions: true,//保留后缀
        maxFieldsSize: 2 * 1024 * 1024//byte//最大可上传大小
    });
    var allFile = [];
    var fileArr = [];
    form.on('progress', function (bytesReceived, bytesExpected) {//在控制台打印文件上传进度
        var progressInfo = {
            value: bytesReceived,
            total: bytesExpected
        };
        // console.log('[progress]: ' + JSON.stringify(progressInfo));
        res.write(JSON.stringify(progressInfo));
    })
        .parse(req, function (err, fields, files) {
            id = fields.id
            if (err) {
                console.log(err);
            }
            allFile.forEach(function (file, index) {
                var fieldName = file[0];
                var types = file[1].name.split('.');
                var date = new Date();
                var ms = Date.parse(date);
                fs.renameSync(file[1].path, form.uploadDir + "/" + types[0] + "." + String(types[types.length - 1]));//重命名文件，默认的文件名是带有一串编码的，我们要把它还原为它原先的名字。
            });
            allFile.forEach(function (file, index) {
                var fieldName = file[0];
                var types = file[1].name.split('.');
                var date = new Date();
                var ms = Date.parse(date);
                fileArr[index] = file[1].path, form.uploadDir + "/" + types[0] + "." + String(types[types.length - 1])
            });
            db.queryArgs($sqlCommands.user_status.insertThereIcons,
                [id,fileArr[0],fileArr[1],fileArr[2]],
                function (err, result) {
                    if (err) {
                        console.log(err)
                    }
                    // 以json形式，把操作结果返回给前台页面
                    db.doReturn(res, result);
                }
            );

        })
        .on('file', function (filed, file) {
            allFile.push([filed, file]);//收集传过来的所有文件
        })
        .on('end', function () {
            res.end('上传成功！');
        })
        .on('error', function (err) {
            console.error('上传失败：', err.message);
            next(err);
        })
}

// 显示所有
function findAllType(req, res, next) {
    // 执行Query
    db.query($sqlCommands.user_status.findAllType,
        function (err, result) {
            if (err) {
                result = {
                    msg: 'failed'
                };
            }
            // 以json形式，把操作结果返回给前台页面
            // console.log(result)
            db.doReturn(res, result)
        }
    );
}

function up(req,res,next){
    var up='';
    var form = formidable.IncomingForm({
        encoding: 'utf-8',//上传编码
        uploadDir: process.cwd()+"/public/files/user/",//上传目录，指的是服务器的路径，如果不存在将会报错。
        // uploadmpDir:dir.dir.mp_path+"/img/user",
        keepExtensions: true,//保留后缀
        // maxFieldsSize: 2 * 1024 * 1024//byte//最大可上传大小
    });
    form.parse(req,function(error, fields, files){
        // console.log(files.file)
        var types       = files.file.name.split('.');
        var date        = new Date();
        var ms          = Date.parse(date);
        var newName =  ms +"."+String(types[types.length-1])
        var user = fields
        up = form.uploadDir+newName
        // console.log(up)
        fields.icon = form.uploadDir+newName
        // fields.mpIcon = form.uploadmpDir+newName
        var name = "files/"+up.split('/')[up.split('/').length-2]+'/'+up.split('/')[up.split('/').length-1]
        // console.log(fields.mpIcon)
        fs.renameSync(files.file.path,form.uploadDir+newName);
        console.log(files.file.path)
        // fs.renameSync(files.file.path,form.uploadmpDir+newName);
        console.log(fields)
        db.query($sqlCommands.user_status.findMaxOne,
            function (err, result) {
                if (err) {
                    result = {
                        err: err
                    }
                }
                req.body['id'] = result[0].maxid + 1;
                // console.log(fields)
                var param = req.body || req.query || req.params;
                if(fields.pid===""){
                    fields.pid = null
                }
                db.queryArgs($sqlCommands.user_status.insertOne,
                    [fields.pid,param.id, fields.name, fields.address, fields.age, name, fields.discount, fields.creationTime, fields.sex, fields.status, fields.inviCode,fields.password],
                    function (err, result) {
                    console.log(fields)
                        if (err) {
                            console.log(err)
                        }
                        // else{
                        //     res.json({
                        //         msg:"插入成功"
                        //     })
                        // }
                        db.doReturn(res, result);
                    }
                );
            }
        );
    })
}

// 显示所有
function findAllApply(req, res, next) {
    // 执行Query
    db.query($sqlCommands.user_status.findAllApply,
        function (err, result) {
            if (err) {
                result = {
                    msg: 'failed'
                };
            }
            // 以json形式，把操作结果返回给前台页面
            // console.log(result)
            db.doReturn(res, result)
        }
    );
}

function findPid(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.findPid,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}
function updateDiscount(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.updateDiscount,
        [param.discount,param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

function persent(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.persent,
        [param.persent,param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}
function persent1(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.persent1,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}
function persent2(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.persent2,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}
function persent3(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.persent3,
        [param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}
function persent4(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.persent4,
        [param.readyper,param.id],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

function login(req, res, next) {
    var param = req.body || req.params || req.query;
    // 执行Query
    db.queryArgs($sqlCommands.user_status.login,
        [param.name,param.password],
        function (err, result) {
            if (err) {
                console.log(err)
            }
            // 以json形式，把操作结果返回给前台页面
            db.doReturn(res, result);
        }
    );
}

// exports
module.exports = {
    addUserAction: addUserAction,
    findAllAction: findAllAction,
    findOneAction: findOneAction,
    deleteUserById: deleteUserById,
    findAllType: findAllType,
    updateOneInfoAction: updateOneInfoAction,
    uploader: uploader,
    up:up,
    findAllApply:findAllApply,
    findOneByInvi:findOneByInvi,
    findPid:findPid,
    updateDiscount:updateDiscount,
    login:login,
    persent:persent,
    persent1:persent1,
    persent2:persent2,
    persent3:persent3,
    persent4:persent4
};
